package com.gourd.common.dic.service.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.gourd.common.dic.dao.DicDao;
import com.gourd.common.dic.entity.Dic;
import com.gourd.common.dic.service.DicService;
import com.gourd.common.dic.vo.DicVO;
import com.gourd.common.enums.DicTypeEnum;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 *
 * 数据字典明细表 服务实现类
 *
 * @author gourd
 * @since 2019-07-30
 */
@Service
@Transactional
public class DicServiceImpl extends ServiceImpl<DicDao, Dic> implements DicService{

    @Autowired
    private DicDao dicMapper;


    /**
     * 获取树形基本行政单位
     * @return
     */
    @Override
    public List<DicVO> findRegionTree(Boolean needCountry){
        // 树形返回结果
        List<DicVO> regionDataVOList = new ArrayList<>();
        // 查询类型集合
        List<String> typeList;
        // 一级数据类型
        String baseType;
        if(needCountry){
            typeList = Arrays.asList(DicTypeEnum.COUNTRY.getValue(),DicTypeEnum.PROVINCE.getValue(),DicTypeEnum.CITY.getValue(),DicTypeEnum.AREA.getValue());
            baseType =DicTypeEnum.COUNTRY.getValue();
        }else {
            typeList = Arrays.asList(DicTypeEnum.PROVINCE.getValue(),DicTypeEnum.CITY.getValue(),DicTypeEnum.AREA.getValue());
            baseType =DicTypeEnum.PROVINCE.getValue();
        }
        List<Dic> dataList = dicMapper.findRegionData(typeList);
        List<DicVO> allList = new ArrayList<>();
        if(CollectionUtils.isEmpty(dataList)){
            return regionDataVOList;
        }
        // 转换成VO
        for(Dic dic : dataList){
            DicVO dicVO = new DicVO();
            BeanUtils.copyProperties(dic, dicVO);
        }
        // 子行政区域
        List<DicVO> childrenRegionData = new ArrayList<>();
        // 循环查询出的数据
        for(DicVO dicVO : allList){
            if(dicVO.getType().equals(baseType)) {
                //一级行政单位（国家）
                regionDataVOList.add(dicVO);
            } else {
                childrenRegionData.add(dicVO);
            }
        }
        // 组装树形数据
        for(DicVO dicVO : childrenRegionData) {
            for(DicVO parent : allList) {
                if(dicVO.getParentCode().equals(parent.getCode())) {
                    if(parent.getChildren() == null) {
                        parent.setChildren(new ArrayList<>());
                    }
                    parent.getChildren().add(dicVO);
                    break;
                }
            }
        }
        return regionDataVOList;
    }


}

